﻿using Pay.IService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Pay.DTO;
using Pay.TO;
using Pay.Token.Utils;
using System.Threading.Tasks;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using Flurl.Http;
using Pay.Core;
using System.Text;

namespace Pay.Token.Controllers {
    /// <summary>
    /// 拓垦分销商城
    /// </summary>
    [AppAuthorize("Member")]
    public class DistributionMallController : GeneralController {
        private IProductService _iProductService;
        private IOrderService _iOrderService;
        private IMerchantService _iMerchantService;
        private ITokenShopSubjectService _iTokenShopSubjectService;
        private IAdvertisementService _iAdvertisementService;
        private IRedRecordService _iRedRecordService;
        private IShopInfoService _iShopInfoService;
        private ISettingService _iSettingService;
        private IActivityService _iActivityService;
        private ICartService _iCartService;
        private IProductActivityService _iProductActivityService;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="iProductService"></param>
        /// <param name="iOrderService"></param>
        /// <param name="iMerchantService"></param>
        /// <param name="iTokenShopSubjectService"></param>
        /// <param name="iAdvertisementService"></param>
        /// <param name="iRedRecordService"></param>
        /// <param name="iShopInfoService"></param>
        /// <param name="iSettingService"></param>
        /// <param name="iActivityService"></param>
        /// <param name="iCartService"></param>
        /// <param name="iProductActivityService"></param>
        public DistributionMallController(IProductService iProductService, IOrderService iOrderService,
            IMerchantService iMerchantService, ITokenShopSubjectService iTokenShopSubjectService,
            IAdvertisementService iAdvertisementService, IRedRecordService iRedRecordService,
            IShopInfoService iShopInfoService, ISettingService iSettingService, IActivityService iActivityService, ICartService iCartService, IProductActivityService iProductActivityService) {
            _iProductService = iProductService;
            _iOrderService = iOrderService;
            _iMerchantService = iMerchantService;
            _iTokenShopSubjectService = iTokenShopSubjectService;
            _iAdvertisementService = iAdvertisementService;
            _iRedRecordService = iRedRecordService;
            _iShopInfoService = iShopInfoService;
            _iSettingService = iSettingService;
            _iActivityService = iActivityService;
            _iCartService = iCartService;
            _iProductActivityService = iProductActivityService;
        }

        /// <summary>
        /// 分销商城首页
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public ActionResult Index() {
            ViewBag.img_url = RequestMethod.token_imgurl;
            merchant_dto merchant = new merchant_dto();
            red_user_dto redcord = new red_user_dto();
            if (UserId > 0) {
                merchant = _iMerchantService.Get(UserId);
                redcord = _iRedRecordService.GetUser(UserId);
            }
            var topic = _iTokenShopSubjectService.GetTokenShopSubjects(ETokenShopSubjectType.Distribution);
            var banner = _iAdvertisementService.AppGetAdvertisementList(new merch_advertisement_query_type() { position_type = (int)EAdvertisementPositionType.TokenMallIndexTop, is_type = false });
            var middleBanner = _iAdvertisementService.AppGetAdvertisementList(new merch_advertisement_query_type() { position_type = (int)EAdvertisementPositionType.TokenMallIndexMiddle, is_type = false });
            var lowerBanner = _iAdvertisementService.AppGetAdvertisementList(new merch_advertisement_query_type() { position_type = (int)EAdvertisementPositionType.TokenMallIndexLower, is_type = false });
            var timeBuyActivityList = _iActivityService.GetIndexTimeBuy();
            ViewBag.merchant = merchant;
            ViewBag.redcord = redcord;
            ViewBag.topic = topic;//专题
            ViewBag.banner = banner;//头部广告
            ViewBag.middleBanner = middleBanner;//中部广告
            ViewBag.lowerBanner = lowerBanner;//中下部广告
            ViewBag.timeBuyActivityList = timeBuyActivityList;//首页限时购活动
            return View();
        }
        /// <summary>
        /// 获取购物车数量
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public JsonResult GetCartCount() {
            var cartCount = 0;
            if (UserId > 0) {
                cartCount = _iCartService.GetCartCount(UserId);//购物车数量
            }
            return Json(ResultToJson.Json(cartCount), JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 云商城首页活动商品列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        [HttpPost, AllowAnonymous]
        public PartialViewResult _IndexActicityProductList(ProductActivityQuery query) {
            ProductActivityQuery activityQuery = new ProductActivityQuery();
            activityQuery.ActivityType = EActivityType.ProductTimeBuy;
            activityQuery.activityId = query.activityId;
            activityQuery.Time = DateTime.Now;
            activityQuery.page = query.page;
            activityQuery.size = query.size;
            var merchant = _iMerchantService.Get(t_RequestMethod.merchant_no);
            activityQuery.merchant_id = merchant.id;
            var list = _iProductActivityService.Gets(activityQuery);
            int userType = 3;
            if (UserId > 0) {
                var curUser = _iMerchantService.Get(UserId);
                userType = (int)curUser.usertype;
            }
            ViewBag.UserType = userType;
            ViewBag.UserId = UserId;
            return PartialView(list);
        }

        /// <summary>
        /// 分销商城第二版
        /// </summary>
        /// <param name="shopId"></param>
        /// <returns></returns>
        [AllowAnonymous]
        public ActionResult Index2(long shopId, string merchant_no) {
            ViewBag.img_url = RequestMethod.token_imgurl;
            var shop = _iShopInfoService.GetShopById(shopId);
            merchant_dto merchant = new merchant_dto();
            red_user_dto redcord = new red_user_dto();
            if (UserId > 0) {
                merchant = _iMerchantService.Get(UserId);
                redcord = _iRedRecordService.GetUser(UserId);
            }
            var topic = _iTokenShopSubjectService.GetTokenShopSubjects(ETokenShopSubjectType.Token);
            var banner = _iAdvertisementService.AppGetAdvertisementList(new merch_advertisement_query_type() { position_type = 6, is_type = false });
            ViewBag.merchant = merchant;
            ViewBag.redcord = redcord;
            ViewBag.topic = topic;
            ViewBag.banner = banner;
            //ViewBag.shop_id = shopId;
            //ViewBag.shop_name = shop.shop_name;
            ViewBag.shop = shop;
            if (!string.IsNullOrEmpty(merchant_no)) {
                //写cookie 分销商户号、缓存key订单号
                byte[] merBytes = Encoding.Default.GetBytes(merchant_no);
                Response.Cookies.Add(new HttpCookie("share_no", Convert.ToBase64String(merBytes)));
            }
            return View();
        }
        /// <summary>
        /// 商品列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        [AllowAnonymous]
        public PartialViewResult _ProductList(GoodsQuery query) {
            GoodsQuery good_query = new GoodsQuery();
            good_query.page = query.page;
            good_query.size = query.size;
            good_query.sale_status = 0;
            good_query.sell_out = false;
            good_query.IsTokenMall = true;
            good_query.keyword = query.keyword;
            var merchant = _iMerchantService.Get(t_RequestMethod.merchant_no);
            good_query.merchant_id = merchant.id;
            var list = _iProductService.GetForActicity(good_query);
            ViewBag.img_url = RequestMethod.token_imgurl;
            int userType = 0;
            if (UserId > 0) {
                var curMerchant = _iMerchantService.Get(UserId);
                userType = (int)curMerchant.usertype;
            }
            ViewBag.UserType = userType;
            return PartialView(list);
        }
        [AllowAnonymous, HttpGet]
        public JsonResult Gets(GoodsQuery query) {
            GoodsQuery good_query = new GoodsQuery();
            good_query.page = query.page;
            good_query.size = query.size;
            good_query.sale_status = 0;
            good_query.sell_out = false;
            good_query.IsTokenMall = true;
            good_query.keyword = query.keyword;
            var merchant = _iMerchantService.Get(t_RequestMethod.merchant_no);
            good_query.merchant_id = merchant.id;
            var list = _iProductService.GetForActicity(good_query);
            return Json(ResultToJson.Json(list), JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 产品详情页
        /// </summary>
        /// <param name="productId"></param>
        /// <param name="shopId"></param>
        /// <param name="merchant_no"></param>
        /// <returns></returns>
        [AllowAnonymous]
        public ActionResult ProductDetail(long productId, string merchant_no,long? shopId) {
            product_dto product;
            try {
                product = _iProductService.GetForActicity(productId, true);
            }
            catch (Exception) {
                return Redirect("/DistributionMall/Index");
            }

            //清空确认订单缓存
            _iOrderService.ClearOrderModelCache(UserId.ToString());

            //分销用户编号
            Response.Cookies["share_no"].Expires = DateTime.Now.AddDays(-1);//清空分销商户号Cookie
            //用于匿名用户购买缓存key
            if (UserId == 0) {
                var key = DtoHelper.GuidTo16String();
                Response.Cookies.Add(new HttpCookie("cache_no", Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(key))));
                _iOrderService.SetOrderModelCache(new token_mall_confirm_order_model { product_id = productId }, key);
            }
            if (!string.IsNullOrEmpty(merchant_no)) {
                //写cookie 分销商户号、缓存key订单号
                byte[] merBytes = Encoding.Default.GetBytes(merchant_no);
                Response.Cookies.Add(new HttpCookie("share_no", Convert.ToBase64String(merBytes)));
            }
         
            //if (product.is_htl == 0) {
            //    if (product.product_skus.Count > 0) {
            //        var firstSku = product.product_skus.FirstOrDefault();
            //        var firstSKuPaths = firstSku.sku_name.Split(new char[] { ';', ':' }).ToArray();
            //        List<sku_info_dto> sku_infos = new List<sku_info_dto>();
            //        List<string[]> sku_names = new List<string[]>();
            //        foreach (var item in product.product_skus) {
            //            List<sku_value_dto> skus = new List<sku_value_dto>();
            //            string[] sku_path = item.sku_path.Split('-').ToArray();
            //            string[] sku_name = item.sku_name.Split(new char[] { ';' }).ToArray();
            //            sku_names.Add(sku_name);
            //        }
            //        var list = sku_names.GroupBy(s => s).Distinct();
            //        foreach (var item in list) {
            //            sku_info_dto sku_info = new sku_info_dto();

            //        }
            //    }

            //}
            merchant_dto merchant = new merchant_dto();
            red_user_dto redcord = new red_user_dto();
            if (UserId > 0) {
                merchant = _iMerchantService.Get(UserId);
                redcord = _iRedRecordService.GetUser(UserId);
            }
            ViewBag.ShareNo = merchant_no;
            ViewBag.Product = product;
            ViewBag.isLogin = (UserId > 0 ? true : false);
            var shop = _iShopInfoService.GetShopById(product.merchant_id);
            ad_dto ad = null ;
          var adlist=  _iAdvertisementService.AppGetAdvertisementList(new merch_advertisement_query_type() { position_type = 12, is_type = false });
            if (adlist.Count > 0) {
                ad = adlist[new Random().Next(adlist.Count)];
            }
            ViewBag.ad = ad;
            ViewBag.shop = shop ?? new shop_info_dto();
            //ViewBag.ShopId = _iShopInfoService.GetShop(productId, shopId.GetValueOrDefault(0));
            ViewBag.merchant = merchant;
            ViewBag.redcord = redcord;
            ViewBag.likeProduct = _iProductService.GetLikeProducts(product.category_id.GetValueOrDefault(0), productId);
            ViewBag.img_url = RequestMethod.token_imgurl;
            return View();
        }
        /// <summary>
        /// 获取商品规格
        /// </summary>
        /// <param name="product_id"></param>
        /// <param name="sku_path"></param>
        /// <returns></returns>
        [AllowAnonymous, HttpGet]
        public JsonResult SkuInfo(long product_id, string sku_path) {
            var result = _iProductService.GetSku(product_id, sku_path);
            return Json(ResultToJson.Json(result), JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 获取商品
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [AllowAnonymous, HttpGet]
        public JsonResult GetProduct(long id) {
           var  product = _iProductService.GetForActicity(id, true);
            return Json(ResultToJson.Json(product), JsonRequestBehavior.AllowGet);
        }
        [AllowAnonymous, HttpGet]
        public JsonResult GetProductCalculate(long id,long skuId) {
            var product = _iProductService.GetCalculateExForActivity(id,skuId, false);
            return Json(ResultToJson.Json(product), JsonRequestBehavior.AllowGet);
        }
        /// <summary>
		/// 图片合成
		/// </summary>
		/// <returns>The merge.</returns>
		/// <param name="product_id">Product identifier.</param>
		/// <param name="merchant_no">Merchant no.</param>
		[HttpGet]
        public FileResult ImageMerge(long product_id, string merchant_no) {
            var product = _iProductService.GetForActicity(product_id);
            var merchant = _iMerchantService.Get(UserId);
            var redrecord = _iRedRecordService.GetUser(UserId);
            string token_img_url = string.Format("http://{0}/content/images/tk_icon@2x.png", Request.Url.Authority);
            string image_url = product.main_image_url;
            string image_100 = string.Format("http://{0}/Content/images/100.png", Request.Url.Authority);
            string share_url = string.Format("http://{0}/DistributionMall/productdetail?productId={1}&merchant_no={2}", Request.Url.Authority, product_id, merchant_no);
            Bitmap canves = new Bitmap(311, 552);//新建大小为311×552大小的画布
            string head_img = (string.IsNullOrEmpty(merchant.photo) ? "http://" + Request.Url.Authority + "/Content/images/my/icon.png" : string.Format("{0}{1}", RequestMethod.token_imgurl, merchant.photo));
            // Bitmap img100 = DownLoadFile(image_100);
            Bitmap headImg = DownLoadFile(head_img);
            Bitmap token_img = DownLoadFile(token_img_url);
            Bitmap productImage = DownLoadFile(image_url);
            Graphics graphics = Graphics.FromImage(canves);
            graphics.FillRectangle(Brushes.White, new Rectangle(0, 0, 311, 552));
            //底部背景颜色
            graphics.FillRectangle(new SolidBrush(Color.FromArgb(243, 243, 243)), new Rectangle(0, 452, 311, 150));
            Font font = new Font("微软雅黑", 10, FontStyle.Regular);
            Brush brush = new SolidBrush(Color.Gray);
            //价格
            Brush price = new SolidBrush(Color.FromArgb(208, 2, 27));
            string price_str = string.Empty;
            if(product.price > 0) {
                price_str += "￥" + product.price.ToString("0.##");
            }
            if(product.price >0 && (product.activity_ex != null && product.activity_ex.activity_red_drill > 0)) {
                price_str += "+";
            }
            if (product.activity_ex != null && product.activity_ex.activity_red_drill > 0) {
                price_str += product.activity_ex.activity_red_drill.ToString("0.######") + " 红钻";
            }
            graphics.DrawString(price_str, new Font("微软雅黑", 10, FontStyle.Bold), price, 80, 405);
            graphics.DrawString("现在只要:", new Font("微软雅黑", 10, FontStyle.Regular), brush, 20, 405);
            //原价
            Brush mPrice = new SolidBrush(Color.FromArgb(102, 102, 102));
            graphics.DrawString(product.market_price.ToString("c"), new Font("微软雅黑", 10, FontStyle.Strikeout), mPrice, 50, 380);
            graphics.DrawString("原价:", new Font("微软雅黑", 10, FontStyle.Regular), brush, 20, 380);
            //标题
            Brush title = new SolidBrush(Color.FromArgb(71, 71, 71));
            for (int i = 0; i < 3; i++) {
                int plength = product.name.Length;
                if (plength >= i * 10) {
                    graphics.DrawString(product.name.Substring(10 * i, plength < (i + 1) * 10 ? (plength + 10 - (i + 1) * 10) : 10), new Font("微软雅黑", 10, FontStyle.Bold), title, 20, 330 + i * 15);
                }
            }
            //邀请码
            graphics.DrawString("-------", new Font("微软雅黑", 10, FontStyle.Regular), new SolidBrush(Color.Red), 75.5f, 462);
            graphics.DrawString("邀请码", new Font("微软雅黑", 10, FontStyle.Regular), brush, 135.5f, 462);
            graphics.DrawString("-------", new Font("微软雅黑", 10, FontStyle.Regular), new SolidBrush(Color.Red), 195.5f, 462);
            graphics.DrawString(redrecord.invitation_code, new Font("微软雅黑", 20, FontStyle.Regular), new SolidBrush(Color.Red), 96.5f, 487);

            //第一张图片
            graphics.DrawImage(productImage, 0, 100, 311, 211);
            //token 图标
            graphics.DrawImage(token_img, 30, 15, 30, 30);
            //token 
            graphics.DrawString("拓垦", new Font("微软雅黑", 10, FontStyle.Bold), brush, 60, 20);
            //100包邮
            // graphics.DrawImage(img100, 40, 430, 110, 110);
            graphics.FillPie(new SolidBrush(Color.FromArgb(243, 243, 243)), new Rectangle(215, 15, 40, 40), 90, 180);
            graphics.FillRectangle(new SolidBrush(Color.FromArgb(243, 243, 243)), 230, 15, 81, 40);
            graphics.DrawImage(headImg, 220, 25, 20, 20);
            graphics.DrawString(merchant.name, new Font("微软雅黑", 10, FontStyle.Regular), new SolidBrush(Color.FromArgb(208, 2, 27)), 245, 20);
            graphics.DrawString("邀请您购买", new Font("微软雅黑", 10, FontStyle.Regular), brush, 245, 32.5f);
            //二维码
            Bitmap codeUrl = QRCodeHelper.CreateImgCode(share_url, 20);
            graphics.DrawImage(codeUrl, 195, 330, 90, 90);


            MemoryStream ms = new MemoryStream();
            canves.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            graphics.Dispose();
            return File(ms.ToArray(), "image/jpeg");
        }
        /// <summary>
        /// 搜索
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public ActionResult Search(long? shopId) {
            ViewBag.shop_id = shopId.GetValueOrDefault(0);
            return View();
        }
        /// <summary>
        /// 商品搜索结果
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public ActionResult SearchResult(long? shopId, string keyword) {
            ViewBag.img_url = RequestMethod.token_imgurl;
            merchant_dto merchant = new merchant_dto();
            red_user_dto redcord = new red_user_dto();
            if (UserId > 0) {
                merchant = _iMerchantService.Get(UserId);
                redcord = _iRedRecordService.GetUser(UserId);
            }
            ViewBag.merchant = merchant;
            ViewBag.redcord = redcord;
            ViewBag.shop_id = shopId.GetValueOrDefault(0);
            ViewBag.keyword = keyword;
            return View();
        }
        /// <summary>
        /// 商品搜索结果
        /// </summary>
        /// <param name="shopId"></param>
        /// <returns></returns>
        [AllowAnonymous]
        public ActionResult SearchShopResult(long shopId) {
            ViewBag.img_url = RequestMethod.token_imgurl;
            merchant_dto merchant = new merchant_dto();
            red_user_dto redcord = new red_user_dto();
            if (UserId > 0) {
                merchant = _iMerchantService.Get(UserId);
                redcord = _iRedRecordService.GetUser(UserId);
            }
            ViewBag.merchant = merchant;
            ViewBag.redcord = redcord;
            ViewBag.shop_id = shopId;
            return View();
        }
        /// <summary>
        /// 下载图片
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        private Bitmap DownLoadFile(string url) {
            byte[] bytes = url.GetBytesAsync().Result;
            MemoryStream ms = new MemoryStream(bytes);
            return new Bitmap(ms);

        }
        private Image CutEllipse(Image img, Rectangle rec, Size size) {
            Bitmap bitmap = new Bitmap(size.Width, size.Height);
            using (Graphics g = Graphics.FromImage(bitmap)) {
                using (TextureBrush br = new TextureBrush(img, WrapMode.Clamp, rec)) {
                    br.ScaleTransform(bitmap.Width / (float)rec.Width, bitmap.Height / (float)rec.Height);
                    g.SmoothingMode = SmoothingMode.AntiAlias;
                    g.FillEllipse(br, new Rectangle(Point.Empty, size));
                }
            }
            return bitmap;
        }

    }
}